﻿@page "/BlazorEvent"

@inject IJSRuntime JS
@using Microsoft.JSInterop;

<h3>BlazorEvent</h3>

<script src="./BlazorEvent.js"></script>

@code {

    private DotNetObjectReference<BlazorEvent> dotNetObjectReference;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        dotNetObjectReference = DotNetObjectReference.Create(this);
        await JS.InvokeVoidAsync("import", "./BlazorEvent.js");
        if (firstRender)
        {
            await JS.InvokeVoidAsync("removeEventListener1", dotNetObjectReference,"beforeunload");
            await JS.InvokeVoidAsync("addEventListener1", "beforeunload");
        }
    }

    public void Dispose()
    {
        _ = JS.InvokeVoidAsync("removeEventListener1", "beforeunload");
    }

    /// <summary>
    /// 页面离开回调
    /// </summary>
    /// <returns></returns>
    [JSInvokable("CallbackBeforeUnload")]
    private async Task CallbackBeforeUnload()
    {
        // 用户离开页面时的逻辑处理
        System.Console.WriteLine("用户即将离开页面");
    }
}
